package com.gack.business.service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gack.business.dao.InviteToEnterpriseDao;
import com.gack.business.dao.InviteToEnterpriseDao.Friend;
import com.gack.business.model.InviteToEnterpriseRecord;
import com.gack.business.model.Message;
import com.gack.business.repository.DownloadUrlRepository;
import com.gack.business.repository.EnterpriseRepository;
import com.gack.business.repository.InviteToEnterpriseRecordRepository;
import com.gack.business.repository.MessageRepository;
import com.gack.business.repository.UserEnterpriseDepartmentPositionRepository;
import com.gack.business.repository.UserRepository;
import com.gack.helper.common.util.MapAsReturn;
import com.gack.helper.common.util.SendCode;

/**
 * 
 * @author ws
 * 2018-8-20
 */
@Transactional
@Service
public class InviteToEnterpriseService implements InviteToEnterpriseServiceInterface {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private UserEnterpriseDepartmentPositionRepository userEnterpriseDepartmentPositionRepository;
	@Autowired
	private InviteToEnterpriseDao inviteToEnterpriseDao;
	@Autowired
	private InviteToEnterpriseRecordRepository inviteToEnterpriseRecordRepository;
	@Autowired
	private MessageRepository messageRepository;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private EnterpriseRepository enterpriseRepository;
	@Autowired
	private DownloadUrlRepository downloadUrlRepository;
	
	/**
	 * 好友邀请列表
	 * @param inviterId 邀请者id
	 * @param enterpriseId 公司id
	 * @return  status:error/success msg:错误或成功消息  friendList:好友列表
	 */
	@Override
	public Map<String, Object> friendListForInvitation(String inviterId, String enterpriseId){
		if(userEnterpriseDepartmentPositionRepository.countByUserIdAndEnterpriseId(inviterId, enterpriseId) == 0){
			return MapAsReturn.setStatusError("非法用户操作");
		}
		
		List<InviteToEnterpriseDao.Friend> list = inviteToEnterpriseDao.friendList(inviterId, enterpriseId);
		
		Comparator<InviteToEnterpriseDao.Friend> comparator = new Comparator<InviteToEnterpriseDao.Friend>(){
			@Override
			public int compare(Friend o1, Friend o2) {
				String s1 = o1.getName_for_show();
				String s2 = o2.getName_for_show();
				return s1.compareTo(s2);
			}
		};
		
		return MapAsReturn.setStatusSuccess("friendList", list);
	}
	
	/**
	 * 通过好友邀请渠道,发送邀请 
	 * @param inviterId 邀请者id
	 * @param enterpriseId 公司id
	 * @param inviteeIds 被邀请者id(id1;id2;id3)
	 * @return status:error/success  msg:错误或成功消息   illegalUsername1:已加入公司的手机号  illegalUsername2:已被邀请的手机号
	 */
	@Override
	public Map<String, Object> inviteByFriend(String inviterId, String enterpriseId, String inviteeIds){
		//判断是否存在非法邀请
		Map<String, Object> map = illegalUsernameByIdsAboutInvitation(inviterId, enterpriseId, inviteeIds);
		if(null != map){
			return map;
		}
		
		String[] inviteeIdArray = inviteeIds.split(";");
		
		for(String element : inviteeIdArray){
			String inviteeUsername = userRepository.findUsernameById(element);
			Date date = new Date();
			InviteToEnterpriseRecord iter = insertIntoInviteToEnterpriseRecord(inviterId, element, inviteeUsername, enterpriseId, "friend", null, date);//保存邀请记录
			sendInMail(inviterId, element, enterpriseId, iter.getId(), date);//发送站内信
			sendShortMail(inviterId, inviteeUsername, enterpriseId, iter.getId(), date);//发送短信,并保存发送记录
		}

		return MapAsReturn.setStatusSuccess(null, null);
	}
	
	/**
	 * ①获取已加入公司的人员手机号②获取已被该用户邀请加入该公司的人员手机号
	 * @param inviterId 邀请者id
	 * @param enterpriseId 公司id
	 * @return status:error/success  msg:错误或成功消息   employeeUsernameList:已加入公司的人员手机号   waitingForPassUsernameList:已被邀请的人员手机号
	 */
	@Override
	public Map<String, Object> markContactsAttribute(String inviterId, String enterpriseId){
		List<String> employeeUsernameList = userEnterpriseDepartmentPositionRepository.findUsernameByEnterpriseId(enterpriseId);
		List<String> waitingForPassUsernameList = inviteToEnterpriseDao.usernameAboutWaitingForPass(inviterId, enterpriseId);
		
		Map<String, Object> map = MapAsReturn.setStatusSuccess("employeeUsernameList", employeeUsernameList);
		map.put("waitingForPassUsernameList", waitingForPassUsernameList);
		return map;
	}
	
	/**
	 * 通过通讯录邀请渠道,发送邀请 
	 * @param inviterId 邀请者id
	 * @param enterpriseId 公司id
	 * @param inviteeUsernames 被邀请者手机号(手机号1;手机号2;手机号3)
	 * @return status:error/success  msg:错误或成功消息   illegalUsername1:已加入公司的手机号  illegalUsername2:已被邀请的手机号
	 */
	@Override
	public Map<String, Object> inviteByTelList(String inviterId, String enterpriseId, String inviteeUsernames){
		//判断是否存在非法邀请
		Map<String, Object> map = illegalUsernameByUsernamesAboutInvitation(inviterId, enterpriseId, inviteeUsernames);
		if(null != map){
			return map;
		}
		
		String[] inviteeUsernameArray = inviteeUsernames.split(";");
		
		for(String element : inviteeUsernameArray){
			String inviteeId = userRepository.findIdByUsername(element);
			inviteeId = ((inviteeId == null || inviteeId.trim().length()==0)?null:inviteeId);
			Date date = new Date();
			InviteToEnterpriseRecord iter = insertIntoInviteToEnterpriseRecord(inviterId, inviteeId, element, enterpriseId, "tel_list", null, date);//保存邀请记录
			sendInMail(inviterId, inviteeId==null?element:inviteeId, enterpriseId, iter.getId(), date);//发送站内信
			sendShortMail(inviterId, element, enterpriseId, iter.getId(), date);//发送短信,并保存发送记录
		}

		return MapAsReturn.setStatusSuccess(null, null);
	}
	
	/**
	 * 通过手机号邀请渠道,发送邀请 
	 * @param inviterId 邀请者id
	 * @param enterpriseId 公司id
	 * @param inviteeUsername 被邀请者手机号
	 * @param remarks 备注
	 * @return status:error/success  msg:错误或成功消息   illegalUsername1:已加入公司的手机号   illegalUsername2:已被邀请的手机号
	 */
	@Override
	public Map<String, Object> inviteByPhoneNumber(String inviterId, String enterpriseId, String inviteeUsername, String remarks){
		//判断是否存在非法邀请
		Map<String, Object> map = illegalUsernameByUsernamesAboutInvitation(inviterId, enterpriseId, inviteeUsername);
		if(null != map){
			return map;
		}
		
		String inviteeId = userRepository.findIdByUsername(inviteeUsername);
		inviteeId = ((inviteeId == null || inviteeId.trim().length()==0)?null:inviteeId);
		Date date = new Date();
		InviteToEnterpriseRecord iter = insertIntoInviteToEnterpriseRecord(inviterId, inviteeId, inviteeUsername, enterpriseId, "phone_number", remarks, date);//保存邀请记录
		sendInMail(inviterId, inviteeId==null?inviteeUsername:inviteeId, enterpriseId, iter.getId(), date);//发送站内信
		sendShortMail(inviterId, inviteeUsername, enterpriseId, iter.getId(), date);//发送短信,并保存发送记录
		
		return MapAsReturn.setStatusSuccess(null, null);
	}
	
	/**
	 * 保存邀请加入公司的记录
	 * @param inviterId 邀请者id
	 * @param inviteeId 被邀请者id
	 * @param inviteeUsername 被邀请者手机号
	 * @param enterpriseId 公司id
	 * @param inviteFrom 邀请方式(friend, tel_list, phone_number)
	 * @param remarks 邀请人设置的企业备注
	 * @param date 创建时间
	 * @return
	 */
	private InviteToEnterpriseRecord insertIntoInviteToEnterpriseRecord(String inviterId, String inviteeId, String inviteeUsername, String enterpriseId, String inviteFrom, String remarks, Date date){
		InviteToEnterpriseRecord iter = new InviteToEnterpriseRecord();
		iter.setInviterId(inviterId);
		iter.setInviteeId(inviteeId);
		iter.setInviteeUsername(inviteeUsername);
		iter.setEnterpriseId(enterpriseId);
		iter.setRemarks(remarks);
		iter.setInviteFrom(inviteFrom);
		iter.setStatus(2);
		iter.setCreateTime(date);
		return inviteToEnterpriseRecordRepository.save(iter);
	}
	
	/**
	 * 发送关于邀请加入公司的站内信
	 * @param inviterId 邀请者id
	 * @param inviteeId 被邀请者id
	 * @param enterpriseId 公司id
	 * @param detailId 邀请记录id
	 * @param date 创建时间
	 * @return
	 */
	private Message sendInMail(String inviterId, String inviteeId, String enterpriseId, String detailId, Date date){
		String enterpriseName = enterpriseRepository.findNameById(enterpriseId);
		String enterpriseRemarks = userEnterpriseDepartmentPositionRepository.findEnterpriseRemarks(inviterId, enterpriseId);
		String text = enterpriseRemarks + "邀请您加入" + enterpriseName;
		
		Message message = new Message();
		message.setCreateId(inviterId);
		message.setUserid(inviteeId);
		message.setMessage(text);
		message.setTitle("验证消息");
		message.setSendWay(2);
		message.setMesType(1);
		message.setState(2);
		message.setIsRead(0);
		message.setDetailId(detailId);
		message.setCreatetime(date);
		return messageRepository.save(message);
	}
	
	/**
	 * 发送邀请信息,并保存发送短信记录
	 * @param inviterId 邀请者id
	 * @param inviteeUsername 被邀请者手机号
	 * @param enterpriseId 公司id
	 * @param detailId 邀请记录id
	 * @param date 创建时间
	 * @return
	 */
	private Message sendShortMail(String inviterId, String inviteeUsername, String enterpriseId, String detailId, Date date){
		String enterpriseName = enterpriseRepository.findNameById(enterpriseId);
		String enterpriseRemarks = userEnterpriseDepartmentPositionRepository.findEnterpriseRemarks(inviterId, enterpriseId);
		String text = enterpriseRemarks + "邀请您加入" + enterpriseName + "。";
		
		String inviteeId = userRepository.findIdByUsername(inviteeUsername);
		if(null == inviteeId || inviteeId.trim().length() == 0){
			String url = downloadUrlRepository.findAll().get(0).getUrl();
			text += "\r\n\r\n下载地址:" + url;
		}
		
		
		//发送短信
		try{
			SendCode.sendMessage(inviteeUsername, text);
		}catch(Exception e){
			logger.error("发送邀请加入公司的短信时失败。detailId=" + detailId);
		}
		
		//保存发送短信记录
		Message message = new Message();
		message.setCreateId(inviterId);//设置创建者id为邀请者id
		message.setUserid(inviteeUsername);//设置接受者id为被邀请者username
		message.setMessage(text);//设置消息内容
		message.setTitle("短信");//设置标题
		message.setSendWay(1);//设置发送方式为"短信"
		message.setMesType(1);//设置消息类型为"邀请加入公司"
		message.setState(null);//设置消息状态为null
		message.setIsRead(null);//设置读状态为null
		message.setDetailId(detailId);//设置该消息所关联的邀请记录表中的记录
		message.setCreatetime(date);//设置创建时间
		return messageRepository.save(message);//保存消息记录
	}
	
	/**
	 * 找出被邀请者中已加入公司和已被邀请的用户的手机号
	 * @param inviterId 邀请者id
	 * @param enterpriseId 公司id
	 * @param inviteeIds 被邀请者id(id1;id2;id3)
	 * @return 若无非法邀请id,则返回null;否则返回Map集合(illegalUsername1:已加入公司的手机号  illegalUsername2:已被邀请的手机号)
	 */
	private Map<String, Object> illegalUsernameByIdsAboutInvitation(String inviterId, String enterpriseId, String inviteeIds){
		List<String> illegalUsername1 = hasInEnterpriseByUserIds(enterpriseId, inviteeIds);
		List<String> illegalUsername2 = hasInvitedByUserIds(inviterId, enterpriseId, inviteeIds);
		if(illegalUsername1.size() > 0){
			Map<String, Object> map = MapAsReturn.setStatusError("存在非法邀请");
			map.put("illegalUsername1", illegalUsername1);
			if(illegalUsername2.size() > 0){
				map.put("illegalUsername2", illegalUsername2);
			}
			return map;
		}
		if(illegalUsername2.size() > 0){
			Map<String, Object> map = MapAsReturn.setStatusError("存在非法邀请");
			map.put("illegalUsername2", illegalUsername2);
			return map;
		}
		return null;
	}
	
	/**
	 * 找出被邀请者中已加入公司和已被邀请的用户的手机号
	 * @param inviterId 邀请者id
	 * @param enterpriseId 公司id
	 * @param inviteeUsernames 被邀请者id(username1;username2;username3)
	 * @return 若无非法邀请id,则返回null;否则返回Map集合(illegalUsername1:已加入公司的手机号  illegalUsername2:已被邀请的手机号)
	 */
	private Map<String, Object> illegalUsernameByUsernamesAboutInvitation(String inviterId, String enterpriseId, String inviteeUsernames){
		List<String> illegalUsername1 = hasInEnterpriseByUsernames(enterpriseId, inviteeUsernames);
		List<String> illegalUsername2 = hasInvitedByUsernames(inviterId, enterpriseId, inviteeUsernames);
		if(illegalUsername1.size() > 0){
			Map<String, Object> map = MapAsReturn.setStatusError("存在非法邀请");
			map.put("illegalUsername1", illegalUsername1);
			if(illegalUsername2.size() > 0){
				map.put("illegalUsername2", illegalUsername2);
			}
			return map;
		}
		if(illegalUsername2.size() > 0){
			Map<String, Object> map = MapAsReturn.setStatusError("存在非法邀请");
			map.put("illegalUsername2", illegalUsername2);
			return map;
		}
		return null;
	}
	
	/**
	 * 找出已加入公司的手机号
	 * @param enterpriseId 公司id
	 * @param inviteeIds 被邀请者id
	 * @return 已加入公司的手机号集合
	 */
	private List<String> hasInEnterpriseByUserIds(String enterpriseId, String inviteeIds){
		if(StringUtils.isBlank(inviteeIds)){
			return new ArrayList<String>();
		}
		
		return inviteToEnterpriseDao.hasInEnterpriseByUserIds(enterpriseId, inviteeIds);
	}
	
	/**
	 * 找出已加入公司的手机号
	 * @param enterpriseId 公司id
	 * @param inviteeUsernames 被邀请者手机号
	 * @return 已加入公司的手机号集合
	 */
	private List<String> hasInEnterpriseByUsernames(String enterpriseId, String inviteeUsernames){
		if(StringUtils.isBlank(inviteeUsernames)){
			return new ArrayList<String>();
		}
		
		return inviteToEnterpriseDao.hasInEnterpriseByUsernames(enterpriseId, inviteeUsernames);
	}
	
	/**
	 * 找出已被邀请过的手机号
	 * @param inviterId 邀请者id
	 * @param enterpriseId 公司id
	 * @param inviteeIds 被邀请者id(id1;id2;id3)
	 * @return 已被邀请过的手机号集合
	 */
	private List<String> hasInvitedByUserIds(String inviterId, String enterpriseId, String inviteeIds){
		if(StringUtils.isBlank(inviteeIds)){
			return new ArrayList<String>();
		}
		
		return inviteToEnterpriseDao.hasInvitedByUserIds(inviterId, enterpriseId, inviteeIds);
	}
	
	/**
	 * 找出已被邀请过的手机号
	 * @param inviterId 邀请者id
	 * @param enterpriseId 公司id
	 * @param inviteeUsernams 被邀请者手机号(手机号1;手机号2;手机号3)
	 * @return 已被邀请过的手机号集合
	 */
	private List<String> hasInvitedByUsernames(String inviterId, String enterpriseId, String inviteeUsernams){
		if(StringUtils.isBlank(inviteeUsernams)){
			return new ArrayList<String>();
		}
		
		return inviteToEnterpriseDao.hasInvitedByUsernames(inviterId, enterpriseId, inviteeUsernams);
	}
	
}
